/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.tnmk.worktime.gui.tbl;

import java.awt.Component;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import org.tnmk.worktime.service.action.Action;

/**
 * @author Copy from here
 */
public class CheckBoxImageHeaderRenderer implements TableCellRenderer {

  private static final String IMGPATH_CHECKBOX_TRUE = "img/form/checkbox_btn.png";
  private static final String IMGPATH_CHECKBOX_FALSE = "img/form/btn.png";
  private final JTable jtbl;
  private final SelectCellPanel comp;
  private static int i = 0;
  protected int column;
  protected boolean mousePressed = false;

  public CheckBoxImageHeaderRenderer(JTable jtbl, int col) {
    this.jtbl = jtbl;
    comp = new SelectCellPanel();
    comp.setCheckboxImages(IMGPATH_CHECKBOX_TRUE, IMGPATH_CHECKBOX_FALSE);
    comp.setCheckboxValueContainer(true);
    comp.renderCheckbox();

    this.jtbl.getColumnModel().getColumn(col).setHeaderRenderer(this);
    initHeaderClickListener();
  }

  private void initHeaderClickListener() {
    this.jtbl.getTableHeader().addMouseListener(new MouseListener() {
      @Override
      public void mouseClicked(MouseEvent e) {
        clickHeader(e);
        ((JTableHeader) e.getSource()).repaint();
      }

      @Override
      public void mousePressed(MouseEvent e) {
        mousePressed = true;
      }

      @Override
      public void mouseReleased(MouseEvent e) {
      }

      @Override
      public void mouseEntered(MouseEvent e) {
      }

      @Override
      public void mouseExited(MouseEvent e) {
      }

    });
  }

  public void setCheckboxAction(Action selectListener) {
    comp.setAdditionalMouseClickAction(selectListener);
  }

  @Override
  public Component getTableCellRendererComponent(
          JTable table, Object value,
          boolean isSelected, boolean hasFocus, int row, int column) {
    this.column = column;
    return this.comp;
  }

  protected void setColumn(int column) {
    this.column = column;
  }

  public int getColumn() {
    return column;
  }

  public boolean isSelected() {
    return comp.isSelected();
  }

  protected void clickHeader(MouseEvent e) {
    if (mousePressed) {
//      LogUtils.printCaller(this);
      mousePressed = false;
      JTableHeader header = (JTableHeader) (e.getSource());
      JTable clickedTable = header.getTable();
      int clickedColumn = header.columnAtPoint(e.getPoint());
      int modelColumn = clickedTable.convertColumnIndexToModel(clickedColumn);
      if (clickedColumn == this.column && modelColumn != -1) {
        comp.clickCheckBox();
      }
    }
  }

}
